package com.orange.quickback.system.config.oath2config;

import com.orange.quickback.system.dao.user.manage.QBootRoleMenuRepository;
import com.orange.quickback.system.entities.user.manage.QBootRole;
import com.orange.quickback.system.entities.user.manage.QBootRoleMenu;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Resource
    QBootRoleMenuRepository qBootRoleMenuRepository;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object obj) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation)obj).getRequestUrl();
        List<QBootRoleMenu> allMenus = qBootRoleMenuRepository.findAll();
        QBootRoleMenu menuTemp = null;
        int menuTempLength=-1;
        for(QBootRoleMenu menu:allMenus) {
            if (antPathMatcher.match(menu.getPattern(), requestUrl)) {

                if(menu.getPattern().length() > menuTempLength) {
                    menuTemp = menu;
                    menuTempLength = menu.getPattern().length();
                }

            }
        }
        if(menuTemp!=null) {
            List<QBootRole> roles = menuTemp.getQBootRoles();
            String[] roleArr = new String[roles.size()];
            for (int i = 0; i < roleArr.length; i++) {
                roleArr[i] = roles.get(i).getRoleName();
            }
            return SecurityConfig.createList(roleArr);
        }
        else return SecurityConfig.createList("ROLE_visitor");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
